'use strict';

const BaseController = require('../base');
const os = require('os');
const fs = require('fs');

class HandeController extends BaseController {

    async printAttachment() {
        const self = this;
        const { service, ctx } = this;
        const { attachmentList } = ctx.request.body;
        try {
            const result = await service.hande.printAttachment(attachmentList);
            self.sendSuccess(result);
        } catch (error) {
            self.sendFail(attachmentList, "失败" + error);
        }

    }

    async getUserSetting() {
        const self = this;
        const { service, ctx } = this;
        const res = await service.hande.getUserSetting();
        self.sendSuccess(res);
    }
    async setUserSetting() {
        const self = this;
        const { service, ctx } = this;
        const userSetting = ctx.request.body;
        this.app.logger.info('[HandeController] [setUserSetting]: userSetting:%j', JSON.stringify(userSetting));
        if (userSetting == null) {
            const msg = "userSetting cannot be null";
            self.sendFail(null, msg);
            return;
        }

        const res = await service.hande.setUserSetting(userSetting);
        self.sendSuccess(res);
    }

    async getPrinterInfo() {
        const self = this;
        const { service, ctx } = this;
        const query = this.ctx.query;

        if (!query.command) {
            const msg = "command cannot be null";
            self.sendFail(null, msg);
            return;
        }
        if (!query.portName) {
            const msg = "portName cannot be null";
            self.sendFail(null, msg);
            return;
        }
        const res = await service.hande.getPrinterInfo(query.command, query.portName);
        self.sendSuccess(res);

    }

    async getOrderList() {
        const self = this;
        const { service, ctx } = this;
        const authorization = ctx.get('Authorization');
        const data = ctx.request.body;
        const list = await service.hande.getOrderList(data, authorization);
        if (list & list.ResponseInfo.Bridgeship.NewDridgedespatchId) {
            self.sendFail(list, "NewDridgedespatchId or list is null");
            return;
        }
        // const payload = {
        //     "RequestInfo": {
        //         "dridgedespatchid": list.ResponseInfo.Bridgeship.NewDridgedespatchId,
        //         "state": 0
        //     }
        // }
        const payload =  {
            "RequestInfo" : {
              "QueryInfo" : {
                "Status" : "0",
                "ShipOrderId" : list.ResponseInfo.Bridgeship.NewDridgedespatchId,
              }
            }
          }
        const res = await service.hande.getOrderDetails(payload, authorization);
        list["uploadFiles"] = res.ResponseInfo.BridShipDet.Accessory.filter(o=>o.DocAddress!==null&&o.DocAddress!=="");
        self.sendSuccess(list);
    }
    async getPrinterList() {
        const self = this;
        const { service, ctx } = this;
        const res = await service.hande.getPrinterList();
        self.sendSuccess(res);
    }

    async checkPrinter() {
        const self = this;
        const { service, ctx } = this;
        const query = this.ctx.query;

        if (!query.portName) {
            const msg = "portName cannot be null";
            self.sendFail(null, msg);
            return;
        }
        const res = await service.hande.checkPrinter(query.portName);
        self.sendSuccess(res);
    }
    async printOrder() {
        const self = this;
        const { service, ctx } = this;
        const authorization = ctx.get('Authorization');
        const data = ctx.request.body;

        if (!authorization) {
            data.msg = "authorization cannot be null";
            await ctx.render('error.ejs', data);
            return;
        }
        // const payload = {
        //     "RequestInfo": {
        //         "dridgedespatchid": data.shipOrderId,
        //         "state": 1
        //     }
        // }
        const payload =  {
            "RequestInfo" : {
              "QueryInfo" : {
                "Status" : 1,
                "ShipOrderId" : data.shipOrderId,
              }
            }
          }
        const res = await service.hande.getOrderDetails(payload, authorization);

        self.sendSuccess(res);
    }
    async getOrderDetails() {
        const self = this;
        const { service, ctx } = this;
        const authorization = ctx.get('Authorization');
        const data = ctx.data;
        const res = await service.hande.getOrderDetails(data, authorization);

        self.sendSuccess(res);
    }
    async printPage() {
        const self = this;
        const { service, ctx } = this;
        const query = this.ctx.query;
        let data = {
            code: -1,
            msg: "",
            data: {},
            query: query
        }
        if (!query.authorization) {
            data.msg = "authorization cannot be null";
            await ctx.render('error.ejs', data);
            return;
        }
        if (!query.status) {
            data.msg = "status cannot be null";
            await ctx.render('error.ejs', data);
            return;

        }
        if (!query.shipOrderId) {
            data.msg = "shipOrderId cannot be null";
            await ctx.render('error.ejs', data);
            return;
        }
        if (!query.orderId) {
            data.msg = "orderId cannot be null";
            await ctx.render('error.ejs', data);
            return;
        }
        const orderPayload = {
            "RequestInfo": {
                "New_Name": query.orderId
            }
        }
        const list = await service.hande.getOrderList(orderPayload, query.authorization);


        if (query.authorization && query.status && query.shipOrderId) {


            // const payload = {
            //     "RequestInfo": {
            //         "dridgedespatchid": query.shipOrderId,
            //         "state": 0
            //     }
            // }
            const payload =  {
                "RequestInfo" : {
                  "QueryInfo" : {
                    "Status" : "0",
                    "ShipOrderId" : list.ResponseInfo.Bridgeship.NewDridgedespatchId,
                  }
                }
              }
            const res = await service.hande.getOrderDetails(payload, query.authorization);
            const shipDetails = this.getShipDetails(res);
            data.code = 0;
            data.data = {
                payload: payload,
                result: res,
                shipDetails: shipDetails,
                bridgeShip: list.ResponseInfo.Bridgeship,
                page: query.page
            }
        }
        if (query.dataType && query.dataType == "json") {
            self.sendSuccess(data);
        } else {
            await ctx.render('print.ejs', data);
        }
    }

    async printPdfPage() {
        const self = this;
        const { service, ctx } = this;
        const query = this.ctx.query;
        let data = {
            code: -1,
            msg: "",
            data: {},
            query: query
        }
        // if (!query.authorization) {
        //     data.msg = "authorization cannot be null";
        //     await ctx.render('error.ejs', data);
        //     return;
        // }


        if (query.dataType && query.dataType == "json") {
            self.sendSuccess(data);
        } else {
            await ctx.render('print_pdf.ejs', data);
        }
    }
    getShipDetails(res) {
        var shipDetails = [];
        if (res && res.ResponseInfo.BridShipDet.ShipDetail) {
            const resShipDetail = res.ResponseInfo.BridShipDet.ShipDetail;
            resShipDetail.forEach(element => {
                let index = shipDetails.findIndex(sd => { return sd.MatCode == element.MatCode });
                if (index == -1) {
                    shipDetails.push(element);
                }
            });
            shipDetails.forEach(element => {
                const list = resShipDetail.filter(detail => {
                    return detail.MatCode == element.MatCode
                });
                element["SerialNum"] = list.map(obj => obj.SerialNum).join(",");
                element["ActualNum"] = element["SerialNum"].split(",").length;

            })
            return shipDetails; z
        } else {
            return []
        }
    }
}

module.exports = HandeController;
